<script lang="ts" setup>
import PageDialog from "@/components/PageDialog/index.vue";
import {ref} from "vue";
import {OwnerEleContractObj} from "@/api/demoClass";
import {
  addOwnerEle,
  ownerList,
  ownerPaymentList,
  projectList
} from "@/api/demoApi";
import {message} from "@/utils/message";
import {timeThan} from "@/utils/timeFormat";

defineOptions({
  name: "registEleDialog"
});

/**-------------------表单相关-------------------**/
//表单参数
const formData = ref({
  id: null,
  projectId:null,
  ownerId:null,
  paymentId:null,
  paymentName:null,
  eleStart:null,
  eleEnd:null,
  eleCycle:null,
  eleUnit:null,
  isFloat: 0,
  floatCount: null,
  status: 0
})

//表单校验
const formRules = ref({
  paymentId:[{required:true,message:'请选择付款单位',trigger:['blur','change']}],
  eleStart:[
    {required:true,message:'请选择合同开始日期',trigger:['blur','change']},
    {
      validator:(rule:any,value:any,cb:any)=>{
        if(value && formData.value.eleEnd) {
          timeThan(formData.value.eleEnd,value) ? cb(new Error('结束日期不应早于开始日期')) : cb()
        }
      },
      trigger:['blur']
    }
  ],
  eleEnd:[
    {required:true,message:'请选择合同结束日期',trigger:['blur','change']},
    {
      validator:(rule:any,value:any,cb:any)=>{
        if(value && formData.value.eleStart) {
          timeThan(value,formData.value.eleStart) ? cb(new Error('结束日期不应早于开始日期')) : cb()
        }
      },
      trigger:['blur']
    }
  ],
  eleCycle:[{required:true,message:'请选择电费结算周期',trigger:['blur','change']}],
  eleUnit:[{required:true,message:'请输入电费单价',trigger:['blur','change']}],
  isFloat:[{required:true,message:'请选择是否浮动',trigger:['blur','change']}]
})

//项目选项
const projectOptions = ref([])
const ownerOptions = ref([])
const paymentOptions = ref([])
const floatOptions = ref([
  {value:0,label:'否'},
  {value:1,label:'是'}
])
const cycleOptions = [
  {value:0,label:'一月一付'},
  {value:1,label:'一季一付'},
  {value:2,label:'半年一付'},
  {value:3,label:'一年一付'},
]
const getProjectOptions = ()=>{
  projectOptions.value = projectList().map(item=>({value:item.id,label:`${item.projectNo}(${item.projectName})`}))
}
const getOwnerOptions = ()=>{
  ownerOptions.value = ownerList().map(item=>({value:item.id,label:item.ownerName}))
}
const getPaymentOptions = id =>{
  paymentOptions.value = ownerPaymentList(id).map(item=>({value:item.id,label:`${item.paymentName}(${item.account})`}))
}

/**-------------------打开弹框-------------------**/
//标题
const dialogTitle = ref('')
const dialog = ref()
//弹框显示
const dialogShow = (title: string,data?: object)=>{
  dialogTitle.value = title
  if(data) {
    if(title ==='查看') {
      formData.value = {...data}
    }else {
      formData.value.projectId = data.projectId
      formData.value.ownerId = data.ownerId
    }
    getProjectOptions()
    getOwnerOptions()
    getPaymentOptions(data.ownerId)
  }
  dialog.value.dialogVisible = true
}
defineExpose({
  dialogShow
})

/**-------------------事件回调-------------------**/
//选择付款单位
  const selectPayment = (val) =>{
    formData.value.paymentName = paymentOptions.value.filter(item=>item.value === val)[0].label ?? null
}
//取消
const form = ref()
const handlerCancel = ()=> new Promise(async (resolve,reject)=>{
  try{
    await form.value.resetFields()
    formData.value = {
      id: null,
      projectId:null,
      ownerId:null,
      paymentId:null,
      paymentName:null,
      eleStart:null,
      eleEnd:null,
      eleCycle:null,
      eleUnit:null,
      isFloat: 0,
      floatCount: null,
      status: 0
    }
    dialog.value.dialogVisible = false
    resolve({})
  }catch(e){
    console.log(e)
    reject(e)
  }
})
//确认
const emits = defineEmits(['done'])
const handlerConfirm = ()=> new Promise(async (resolve,reject)=>{
  try{
    await form.value.validate()
    //todo 新增、编辑接口
    const newOwnerEle = new OwnerEleContractObj(formData.value)
    const result = addOwnerEle(newOwnerEle)
    if(!result) {
      message("添加成功", { type: "success" });
      await handlerCancel()
      emits('done')
      resolve({})
    }else {
      message(result, { type: "warning" });
      resolve({})
    }
  }catch(e){
    reject(e)
  }
})
</script>

<template>
  <PageDialog ref="dialog" :handler-cancel="handlerCancel" :handler-confirm="handlerConfirm" :title="dialogTitle">
    <el-form ref="form" :disabled="dialogTitle === '查看'" :model="formData" :rules="formRules" label-position="top" label-width="auto">
      <el-form-item label="项目名称" prop="projectId">
        <el-select v-model="formData.projectId" clearable disabled filterable placeholder="请选择项目名称">
          <el-option v-for="(item,index) in projectOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属业主" prop="ownerId">
        <el-select v-model="formData.ownerId" clearable disabled filterable placeholder="请选择所属业主">
          <el-option v-for="(item,index) in ownerOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="付款单位" prop="paymentId">
        <el-select v-model="formData.paymentId" clearable filterable placeholder="请选择付款单位" @change="selectPayment">
          <el-option v-for="(item,index) in paymentOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="起始日期" prop="eleStart">
        <el-date-picker
          v-model="formData.eleStart"
          clearable
          format="YYYY-MM-DD"
          placeholder="请选择合约起始日期"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结束日期" prop="eleEnd">
        <el-date-picker
          v-model="formData.eleEnd"
          clearable
          format="YYYY-MM-DD"
          placeholder="请选择合约结束日期"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结算周期" prop="eleCycle">
        <el-select v-model="formData.eleCycle" clearable filterable placeholder="请选择电费结算周期">
          <el-option v-for="(item,index) in cycleOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="电费单价" prop="eleUnit">
          <el-input-number v-model.number="formData.eleUnit" :controls="false" :precision="2" :step="0.01" placeholder="请输入电费单价"/>
      </el-form-item>
      <el-form-item label="是否浮动" prop="isFloat">
        <el-select v-model="formData.isFloat" clearable filterable placeholder="请选择是否浮动">
          <el-option v-for="(item,index) in floatOptions" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="上浮比例" prop="floatCount">
        <el-input-number v-model.number="formData.floatCount" :controls="false" :disabled="!formData.isFloat" :precision="2" :step="0.01" placeholder="请输入上浮比例，数值表示百分比"/>
      </el-form-item>
    </el-form>
  </PageDialog>
</template>

<style lang="scss" scoped>
:deep(.el-form) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;

  .el-form-item {
    width: 48%;

    .el-input,
    .el-input-number,
    .el-date-picker,
    .el-select {
      width: 100%;
    }
  }
}
</style>
